package o2o.task.sys;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.shop.ShopMemory;
import o2o.cache.system.SysSettingMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.wallet.UserWalletMemory;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.UserType;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.sys.SysSetting;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.PAY_TYPE;
import o2o.dao.PO.wallet.UserWallet;
import o2o.web.actions.wallet.UserWalletMan;
import o2o.web.actions.wallet.WalletAction;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import o2o.system.data.SYS_SETTINGS;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

// 店铺自动提现
@Component
public class ShopAutoPopTask {

    private final static String SHOP_AUTO_POP = "shopAutoPop";

    //秒  分  时  日  月  星期几  年
    @Scheduled(cron = "0 0 0 * * ? ")// 每天0点执行
//    @Scheduled(cron = "0 * * * * ? ")// 测试
//    @Scheduled(cron = "0 * * * * ? ")
    public void shopAutoPop() {
        if (SYS_SETTINGS.SHOP_AUTO_POP_TYPE != null && SYS_SETTINGS.SHOP_AUTO_POP_TYPE == 1) {
            this.shopAutoPopType1();
        } else if (SYS_SETTINGS.SHOP_AUTO_POP_TYPE != null && SYS_SETTINGS.SHOP_AUTO_POP_TYPE == 2) {
            this.shopAutoPopType2();
        }
    }

    // 检测指定天数
    public static void shopAutoPopType1() {
        SysSetting setting = SysSettingMemory.getInstance().getByCode(SHOP_AUTO_POP);
        if (setting == null) {
            return;
        }
        if (StringUtils.isEmpty(setting.getVal())) {
            return;
        }
        Long day = null;
        try {
            day = Long.parseLong(setting.getVal().toString());
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        if (day == null || day <= 0) {
            System.out.println("商家自动提现 天数未设置。。。。。");
            return;
        }
        Long lastTime = null;
        if (StringUtils.isEmpty(setting.getNote())) {
            System.out.println("最后提现时间未设置。。。。。");
            return;
        }
        try {
            lastTime = Long.parseLong(setting.getNote());
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        if (lastTime == null || lastTime < 0) {
            return;
        }
//        Long nowTime = DateUtils.getCurrTime();
//        if ((nowTime + day * 24 * 60 * 60 * 1000L + 5 * 60 * 1000L) < localTime) { // 提现时间加上指定天数后  加上五分中的时间 如果大于当前的时间 就提现
//            // 未到提现日期
//            return;
//        }

        Long nowTime = DateUtils.getCurrTime();
        Long cha = nowTime - (lastTime + day * 24 * 60 * 60 * 1000);
        if (cha + 60 * 60 * 1000 >= 0) { // 到了间隔天
            // 到了提现时间
        } else {
            return;
        }
        List<ShopInfo> shopList = ShopMemory.getInstance().list();
        if (!ValidateUtil.isAbsList(shopList)) {
            return;
        }
        for (int i = 0; i < shopList.size(); i++) {
            ShopInfo shopInfo = shopList.get(i);
            if (null == shopInfo) {
                continue;
            }
            UserWallet wallet = UserWalletMemory.getInstance().getWallet(shopInfo.getOwnUsername());
            if (null == wallet) {
                continue;
            }
            if (wallet.getMoney() <= 0) {
                // 余额没有的时候不再提现
                continue;
            }
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(shopInfo.getOwnUsername());
            if (null == userInfo) {
                continue;
            }
            // 如果有绑定的渠道，直接提现
            if (ValidateUtil.isNotNull(wallet.getAlipay()) && ValidateUtil.isNotNull(wallet.getAlipayRealName())) {
                // 支付宝不为空，提现到支付宝
                WalletAction.moneyPop(userInfo, wallet.getMoney(), PAY_TYPE.ALLIPAY, false, UserType.SHOP_OWNER);
            } else if (ValidateUtil.isNotNull(wallet.getTenpay()) && ValidateUtil.isNotNull(wallet.getTenpayRealName())) {
                // 微信不为空，提现到微信
                WalletAction.moneyPop(userInfo, wallet.getMoney(), PAY_TYPE.WX, false, UserType.SHOP_OWNER);
            } else {
                // 银行卡不为空，直接提现银行卡
                WalletAction.moneyPop(userInfo, wallet.getMoney(), PAY_TYPE.BANK_CARD, false, UserType.SHOP_OWNER);
            }
        }
        // 修改日期
        StringBuilder updateSql = new StringBuilder();
        updateSql.append(" update ").append(PojoTables.SYS_SETTING).append(" set note = '").append(nowTime).append("'")
                .append(" where delFlag = 0 and name = '").append(SHOP_AUTO_POP).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(updateSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SysSettingMemory.getInstance().modifyByCode(SHOP_AUTO_POP);

    }


    // 检测指定天数未提现
    public static void shopAutoPopType2() {
        // 系统是否自动提现
        if (null != SYS_SETTINGS.SHOP_AUTO_POP && SYS_SETTINGS.SHOP_AUTO_POP > 0) {
            // 自动提现天数间隔
            // 获取所有店铺
            List<ShopInfo> shopList = ShopMemory.getInstance().list();
            if (!ValidateUtil.isAbsList(shopList)) {
                return;
            }

            // 获取店铺最后一次提现时间
            StringBuffer sb = new StringBuffer();
            sb.append("SELECT MAX(createtime) tim,username ").append(" FROM ").append(PojoTables.USER_WALLET_POP)
                    .append(" where delFlag =0 and popType = ").append(UserWalletMan.POP)
                    .append(" GROUP BY username");

            List<HashMap<String, Object>> list = null;
            try {
                list = UserDaoSql.getInstance().queryBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 最后提现记录<账号，时间>
            ConcurrentHashMap<String, Long> popMap = new ConcurrentHashMap();
            if (ValidateUtil.isAbsList(list)) {
                for (int i = 0; i < list.size(); i++) {
                    HashMap<String, Object> map = list.get(i);
                    if (null == map) {
                        continue;
                    }
                    popMap.put(map.get("username").toString(), Long.parseLong(map.get("tim").toString()));
                }
            }
            Long time = DateUtils.getCurrTime();// 当前时间
            for (int i = 0; i < shopList.size(); i++) {
                ShopInfo shopInfo = shopList.get(i);
                if (null == shopInfo) {
                    continue;
                }
                boolean needPop = false;// 需要提现
                if (null != popMap && popMap.containsKey(shopInfo.getOwnUsername())) {
                    // 该商家有提现过
                    Long popTime = popMap.get(shopInfo.getOwnUsername());
                    // 判断上次提现时间距离现在的时间是否到了
                    if (time - popTime > SYS_SETTINGS.SHOP_AUTO_POP * 24 * 60 * 60 * 1000) {
                        needPop = true;
                    }
                } else {
                    // 该商家还没有提现过
                    needPop = true;
                }


                if (needPop) {
                    //需要提现
                    // 看下是否绑定了提现渠道
                    UserWallet wallet = UserWalletMemory.getInstance().getWallet(shopInfo.getOwnUsername());
                    if (null == wallet) {
                        continue;
                    }
                    if (wallet.getMoney() <= 0) {
                        // 余额没有的时候不再提现
                        continue;
                    }
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(shopInfo.getOwnUsername());
                    if (null == userInfo) {
                        continue;
                    }
                    // 如果有绑定的渠道，直接提现
                    if (ValidateUtil.isNotNull(wallet.getBankCard()) && ValidateUtil.isNotNull(wallet.getBankName()) && ValidateUtil.isNotNull(wallet.getBankUserName())) {
                        // 银行卡不为空，直接提现银行卡
                        WalletAction.moneyPop(userInfo, wallet.getMoney(), PAY_TYPE.BANK_CARD, UserType.SHOP_OWNER);
                    } else if (ValidateUtil.isNotNull(wallet.getAlipay()) && ValidateUtil.isNotNull(wallet.getAlipayRealName())) {
                        // 支付宝不为空，提现到支付宝
                        WalletAction.moneyPop(userInfo, wallet.getMoney(), PAY_TYPE.ALLIPAY, UserType.SHOP_OWNER);
                    } else if (ValidateUtil.isNotNull(wallet.getTenpay()) && ValidateUtil.isNotNull(wallet.getTenpayRealName())) {
                        // 微信不为空，提现到微信
                        WalletAction.moneyPop(userInfo, wallet.getMoney(), PAY_TYPE.WX, UserType.SHOP_OWNER);
                    }
                }

            }
        }
    }


    public static void main(String[] args) {
//        Long nowTime = DateUtils.getCurrTime();
//        Long nowTime = 1562259600000l;
//        Long jiange = nowTime - (1561996800414l + 3 * 24 * 60 * 60 * 1000);
//        if (jiange + 60 * 60 * 1000 >= 0) { // 到了间隔天
//            System.out.println(jiange / 1000 / 60);
//        }


//        Long nowTime = 1562256001000l;
//        Long lasttime = 1561996870000l;
//        Long jiange = nowTime - (lasttime + 3 * 24 * 60 * 60 * 1000);
//        if (jiange + 60 * 60 * 1000 >= 0) { // 到了间隔天
//            System.out.println(jiange);
//        }l

        Long lastTime = 1561996800414l;
        Long nowTime = 1562256070000l;
        Long cha = nowTime - (lastTime + 3 * 24 * 60 * 60 * 1000);
        if (cha + 60 * 60 * 1000 >= 0) { // 到了间隔天
            // 到了提现时间
            System.out.println("tixian");
        }
    }

}
